package fr.vahren.processing.entity;

import processing.core.PApplet;
import traer.physics.Particle;
import traer.physics.Vector3D;
import fr.vahren.processing.Main;

public class Electron extends Entity {

	private Atom atom;
	private Atom target;

	public Electron(Particle particle, PApplet pA, Atom a) {
		this.particle = particle;
		this.pA = pA;
		setAtom(a);
		this.speed = (int) pA.random(5, 10) * 100;
		anti = a.isAnti();
	}

	public void draw() {
		pA.pushMatrix();
		pA.noStroke();
		if (anti) {
			if (picked) {
				pA.fill(155, 155, 0);
			} else {
				pA.fill(255, 255, 0);
			}
		} else {
			if (picked) {
				pA.fill(100, 100, 255);
			} else {
				pA.fill(0, 0, 255);
			}
		}
		pA.translate(particle.position().x(), particle.position().y(), particle
				.position().z());
		pA.sphere(Main.ATOM_SIZE / 2);
		pA.popMatrix();
		checkVelocity();
	}

	public void checkVelocity() {
		particle.velocity().setX(
				PApplet.min(particle.velocity().x(), Main.MAX_VELOCITY));
		;
		particle.velocity().setY(
				PApplet.min(particle.velocity().y(), Main.MAX_VELOCITY));
		;
		particle.velocity().setZ(
				PApplet.min(particle.velocity().z(), Main.MAX_VELOCITY));
		;
	}

	public void slowDown(int factor) {
		Vector3D v = particle.velocity();
		if (factor == 0) {
			v.set(0, 0, 0);
		} else {
			v.set(v.x() / factor, v.y() / factor, v.z() / factor);
		}
	}

	/**
	 * @return the atom
	 */
	public Atom getAtom() {
		return atom;
	}

	/**
	 * @param atom
	 *            the atom to set
	 */
	public void setAtom(Atom atom) {
		this.atom = atom;
		atom.addElectron(this);
	}

	/**
	 * @return the target
	 */
	public Atom getTarget() {
		return target;
	}

	/**
	 * @param target
	 *            the target to set
	 */
	public void setTarget(Atom target) {
		this.target = target;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Electron [particle=" + particle + "]";
	}

	public void removeAtom() {
		atom.getElectrons().remove(this);
		atom = null;
	}

	public void sendImpulsion(Vector3D i, float strength) {
		Vector3D v = particle.velocity();
		Vector3D iNorm = normalize(i).multiplyBy(strength);

		v.set((v.x() + iNorm.x()) / 2, (v.y() + iNorm.y()) / 2,
				(v.z() + iNorm.z()) / 2);

	}

	private Vector3D normalize(Vector3D v) {
		float len = v.length();
		return new Vector3D(v.x() / len, v.y() / len, v.z() / len);
	}

}
